package com.thread.pool;

import java.util.concurrent.RecursiveAction;
import java.util.concurrent.RecursiveTask;

// 继承 RecursiveAction 来实现可分解的任务
public class CalTask extends RecursiveTask<Integer> {

    // 每个小任务最多累加20个数字
    public static final int THRESHOLD = 20;
    private int arr[];
    private int start;
    private int end;

    // 累加从start到end的数组元素
    public CalTask(int[] arr, int start, int end) {
        this.arr = arr;
        this.start = start;
        this.end = end;
    }

    // 打印从start到end的任务
    public CalTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        // 当end与start之间的差小于THRESHOLD时，开始打印
        if (end - start < THRESHOLD) {
            for (int i = start; i < end; i++) {
                sum += arr[i];
            }
            return sum;
        } else {
            // 当end与start之间的差大于THRESHOLD时，即要累加的数超过20
            int middle = (start + end) / 2;
            CalTask left = new CalTask(arr, start, middle);
            CalTask right = new CalTask(arr, middle, end);
            // 并行执行两个小任务
            left.fork();
            right.fork();
            // 把两个小任务累加的结果合并起来
            return left.join() + right.join();
        }
    }


}
